<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名称" prop="studentName">
        <el-input
          v-model="queryParams.studentName"
          placeholder="请输入学生姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['teach:student:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['teach:student:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['teach:student:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-if="false"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['teach:student:export']"
        >导出</el-button>
      </el-col>

      <el-popover
        placement="bottom"
        ref="popoverRef"
        title="学生标签查看"
        width="300"
        trigger="click"
        >
        <el-card class="box-card">
          <div v-for="o in tagsList" :key="o.tagId" class="text item">
            {{'标签:' }}<span @click="handleDeleteTags(o)" style="margin-left: 10px;cursor: pointer">{{o.tagName }}</span>

          </div>
        </el-card>
        <el-button
          :disabled="single" @click="handleTags" type="info" plain
          v-hasPermi="['teach:student:edit']"
                   size="mini" slot="reference">标签管理</el-button>
      </el-popover>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="studentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column v-if="false" label="用户ID" align="center" prop="studentId" />
      <el-table-column label="学生姓名" align="center" prop="studentName" />
      <el-table-column v-if="false" label="学生昵称" align="center" prop="nickName" />
      <el-table-column v-if="false" label="用户类型" align="center" prop="userType" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.teach_student_type" :value="scope.row.userType"/>
        </template>
      </el-table-column>
      <el-table-column label="所在学校" align="center" prop="email" />
      <el-table-column label="年级" align="center" prop="password" />
      <el-table-column label="性别" align="center" prop="sex" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex"/>
        </template>
      </el-table-column>
      <el-table-column label="手机号码" align="center" prop="phonenumber" />
      <el-table-column label="头像地址" align="center" prop="avatar" >
        <template slot-scope="scope">
          <span v-if="scope.row.avatar !== null && scope.row.avatar !== ''">已上传</span>
          <span v-else>未上传</span>
        </template>
      </el-table-column>
      <el-table-column v-if="false" label="头像地址" align="center" prop="avatar" />
      <el-table-column v-if="false" label="密码" align="center" prop="password" />
      <el-table-column label="状态" align="center" prop="status" >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column v-if="false" label="最后登录IP" align="center" prop="loginIp" />
      <el-table-column v-if="false" label="最后登录时间" align="center" prop="loginDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.loginDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="false" label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['teach:student:edit']"
          >修改</el-button>

          <el-button
            size="mini"
            type="text"
            @click="handleAddTags(scope.row)"
            v-hasPermi="['teach:studentTag:add']"
          >添加标签</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['teach:student:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改学生信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="学生名称" prop="studentName">
          <el-input  v-model="form.studentName" placeholder="请输入用户名称" />
        </el-form-item>
        <el-form-item v-if="false" label="学生昵称" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入用户昵称" />
        </el-form-item>
        <el-form-item label="性别">
          <el-select style="width: 100%" v-model="form.sex" placeholder="请选择">
            <el-option
              v-for="dict in dict.type.sys_user_sex"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所在学校" prop="email">
          <el-input v-model="form.email" placeholder="请输入所在学校" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="年级" prop="password">
          <el-input v-model="form.password" placeholder="请输入年级" />
        </el-form-item>

        <el-form-item label="标签" prop="tag">
          <span style="margin: 0 10px;background-color: #d2d1d1" v-for="item in studentTags" >{{item.tagId}}</span>
        </el-form-item>

        <el-form-item label="个人头像" prop="avatar">
          <div class="text-center">
            <studentAvatar :key="childKey" :data="parentData" @custom-event="handleEvent" :user="user" />
          </div>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="添加学生标签" center
      :visible.sync="visible" width="300px" append-to-body>
      <el-form :model="formStudentTag" label-width="60px">
        <el-form-item label="标签" prop="tag">
          <el-input v-model="formStudentTag.tagName" placeholder="请输入标签" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitTagForm">确 定</el-button>
        <el-button @click="visible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStudent, getStudent, delStudent, addStudent, updateStudent,changeStudentStatus } from "@/api/teach/student";
import studentAvatar from '../../system/user/profile/studentAvatar.vue'
import { addTag, delByTag, getTagList } from '../../../api/teach/studentTag'

export default {
  name: "Student",
  components: { studentAvatar },
  dicts: ['sys_user_sex','teach_student_type'],
  data() {
    return {
      user: {},
      childKey:0,
      parentData: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学生信息表格数据
      studentList: [],
      studentTags: [],
      tagsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      visible: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        studentName: null,
        nickName: null,
        status: null,
      },
      // 表单参数
      form: {},
      formStudentTag: {},
      // 表单校验
      rules: {
        studentName: [
          { required: true, message: "用户名称不能为空", trigger: "blur" }
        ],
      }
    };
  },
  provide() {
    return {
      sharedData: () => {
         return this.form.avatar
      },
      studentId: () => {
        return this.form.studentId
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询学生信息列表 */
    getList() {
      this.loading = true;
      listStudent(this.queryParams).then(response => {
        this.studentList = response.rows;
        this.studentList.forEach(element => {
          if(element.avatar !== null && element.avatar !== '') {
            element.avatar = process.env.VUE_APP_BASE_API + element.avatar;
          }
        })
        // console.log(this.studentList);
        this.total = response.total;
        this.loading = false;
      });
    },
    handleEvent(data) {
      // console.log('Received data from child avatar:', data);
      this.form.avatar = data
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        studentId: null,
        deptId: null,
        studentName: null,
        nickName: null,
        userType: null,
        email: null,
        phonenumber: null,
        sex: null,
        avatar: null,
        password: null,
        status: "0",
        delFlag: null,
        loginIp: null,
        loginDate: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.studentName + '"吗？').then(function() {
        return changeStudentStatus(row.studentId, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.studentId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加学生信息";
      this.childKey ++
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const studentId = row.studentId || this.ids
      this.getStudentInfo(studentId)
      this.open = true;
      this.title = "修改学生信息";
      this.childKey ++
    },
    getStudentInfo(studentId){
      getStudent(studentId).then(response => {
        this.form = response.data;
        // console.log(this.form);
        if(this.form.avatar !== null && this.form.avatar !== '') {
          this.form.avatar = process.env.VUE_APP_BASE_API + this.form.avatar;
        }
        this.studentTags = []
        this.form.studentTags.forEach(tag => {
          this.studentTags.push({
            'tagId': tag,
          })
        })
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.studentId != null) {
            updateStudent(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStudent(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleAddTags(row){
      this.visible = true
      // console.log(row)
      this.formStudentTag = {
        studentId: row.studentId,
        studentName: row.studentName,
        tagName: null,
      }
    },
    handleTags(row){
      this.tagsList = []
      const studentId = row.studentId || this.ids
      getTagList(studentId[0]).then(response => {
        // console.log(response);
        if (response.code === 200) {
          this.tagsList = response.rows;
        }
      })
    },
    handleDeleteTags(row){
      // console.log(row)
      this.$modal.confirm('是否确认删除标签为"' + row.tagName + '"的数据？').then(() => {
        delByTag(row.tagId).then(response => {
          if (response.code === 200) {
            this.$modal.msgSuccess("删除成功");
          }
          this.$refs.popoverRef.doClose();
        })
      }).catch(() => {
        this.$modal.msg("取消删除");
      });
    },
    submitTagForm(){
      // console.log(this.formStudentTag);
      if (this.formStudentTag.tagName === null || this.formStudentTag.tagName === "" ) {
        this.$modal.msgWarning("请输入标签");
        return;
      }
      addTag(this.formStudentTag).then(response => {
        // console.log(response);
        if (response.code === 200) {
          this.$modal.msgSuccess("添加成功");
        }
        else {
          this.$modal.alertError("添加失败")
        }
        this.visible = false;
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const studentIds = row.studentId || this.ids;
      this.$modal.confirm('是否确认删除学生信息编号为"' + studentIds + '"的数据项？').then(function() {
        return delStudent(studentIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('teach/student/export', {
        ...this.queryParams
      }, `student_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
